package com.flesler.stickjoy.applet;

import java.applet.Applet;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;

import netscape.javascript.JSObject;

import com.flesler.stickjoy.core.StickJoy;
import com.flesler.stickjoy.core.StickJoyWrapper;

@SuppressWarnings("serial")
public class AppletStickJoyWrapper extends Applet implements StickJoyWrapper {

	private ByteArrayOutputStream out;
	private JSObject embed;
	private String method;
	private StickJoy sj;
	
	public AppletStickJoyWrapper() 
	{
		
	}
	
	public void init()
	{
		// TODO: Put the embed here instead
		embed = JSObject.getWindow(this);
		method = getParameter("method");
		
		out = new ByteArrayOutputStream();
		
		sj = new StickJoy(this);
		sj.sendAll();
		sj.startPolling();
	}

	@Override
	public void flush() {
		if (out.size() == 0)
			return;
		
		String bytes = out.toString();
		out.reset();
		
		embed.call(method, new Object[]{ bytes });
	}

	@Override
	public OutputStream getStream() {
		return out;
	}

	public static void main(String[] args) {
		new AppletStickJoyWrapper();
	}

}
